package org.xx.armory.swing.components;

import org.xx.armory.commons.MapBuilder;
import org.xx.armory.commons.Version;
import org.xx.armory.swing.Application;
import org.xx.armory.swing.UIUtils;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;

import static org.apache.commons.lang3.StringUtils.startsWithAny;
import static org.xx.armory.swing.UIUtils.UPDATE_UI;

/**
 * 关于对话框。
 */
public class AboutDialog
        extends DialogPane {
    public AboutDialog() {
        setTitle(getTitle() + " " + Application.title());

        controller().setText("app-product-name", "<html><strong>" + Application.productName() + "</strong></html>");

        final Version version = Application.version();
        controller().setText("app-version", version != null ? version.toString() : "");

        controller().setText("app-copyright", Application.copyright());

        CompletableFuture
                .supplyAsync(this::getSysProperties)
                .thenAcceptAsync(this::updateSystemProperties, UPDATE_UI)
                .exceptionally(UIUtils::defaultDumpThrowable);
    }

    private Collection<Map<String, Object>> getSysProperties() {
        final Properties properties = System.getProperties();

        final List<Map<String, Object>> result = new ArrayList<>(properties.size());

        final String[] names = properties.stringPropertyNames().stream()
                                         .filter(name -> startsWithAny(name, "java.", "user.", "os."))
                                         .toArray(String[]::new);
        for (final String name : names) {
            result.add(new MapBuilder<String, Object>()
                               .put("name", name)
                               .put("value", properties.getProperty(name))
                               .buildHashMap());
        }

        return result;
    }

    private void updateSystemProperties(
            Collection<? extends Map<String, Object>> data
    ) {
        final JTable table = controller().get(JTable.class, "sys-properties");
        final TypedTableModel model = (TypedTableModel) table.getModel();
        model.setAllRows(data);

        pack();
    }
}
